#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@desc: .

@Project ：kuberCloudSDK
@File ：kuberCloud.py
@Author ：admin
@Date ：2024/3/19 18:42 
"""
import base64
import json
from _sha1 import sha1

import requests

from kuberCloudTest.api import KuberCloudHttpRequest
from kuberCloudTest.common.kuberlogs.log import kuberCloudLog
from kuberCloudTest.common.utils import _getUrl
from kuberCloudTest.config import GlobalVars
from kuberCloudTest.exception import KuberCloudException
from kuberCloudTest.urls import Urls


class KuberCloudSDK(object):

    def __init__(self, accessKeyId, accessKeySecret, host, port):
        self._accessKeyId = accessKeyId
        self._accessKeySecret = accessKeySecret
        self._host = host
        self._port = port

        if not self._accessKeyId or not self._accessKeySecret:
            raise KuberCloudException('params error', 'accessKeyId or accessKeySecret is none')
        if not self._host or not self._port:
            raise KuberCloudException('params error', 'host or port is none')

        # 初始化变量值，全局使用
        GlobalVars.HOST = self._host
        GlobalVars.PORT = self._port
        GlobalVars.ACCESS_KEYID = self._accessKeyId
        GlobalVars.ACCESS_KEY_SECRET = self._accessKeySecret

    @staticmethod
    def _getSignature():
        Access = GlobalVars.ACCESS_KEYID + GlobalVars.ACCESS_KEY_SECRET
        return base64.b64encode(sha1(Access.encode('utf-8')).digest()).decode('utf-8')

    def getAccessToken(self):
        try:
            params = {'accessKeyId': GlobalVars.ACCESS_KEYID, 'signature': self._getSignature()}
            response = requests.get(_getUrl(GlobalVars.HOST, GlobalVars.PORT, Urls.getAccessToken.value), params=params)
            if response.status_code != 200:
                raise KuberCloudException('internal error', 'internal error')
            content = json.loads(response.content.decode())
            if content['code'] != 1:
                raise KuberCloudException('get access-token error', content['msg'])
            accessToken = content.get('accessToken', None)
            if not accessToken:
                raise KuberCloudException('get access-token error', 'access-token is none')
            zoneIds = content.get('zoneIds', [])
            projectIds = content.get('projectIds', [])
            if len(projectIds) > 1 or len(zoneIds) > 1:
                kuberCloudLog.info('hahahhahhahah')
                kuberCloudLog.warning('get access-token error')
                kuberCloudLog.error('get access-token error')
                kuberCloudLog.warning('more than one project or zone exists, please specify a project or zone first. '
                                      'You can use changeZone or changeProject to switch zone or project')
            return accessToken
        except KuberCloudException as kuberCloudException:
            kuberCloudLog.error('internal error: get access-token failed: {}'.format(kuberCloudException.message))
            raise KuberCloudException(kuberCloudException.reason, kuberCloudException.message)
        except Exception as exception:
            kuberCloudLog.error('internal error: get access-token failed: {}'.format(exception.args[0]))
            raise KuberCloudException('internal error', exception.args[0])

    @staticmethod
    def _get_http_request(accessToken):
        return KuberCloudHttpRequest(accessToken)

    def refreshAccessToken(self, accessToken):
        return self._get_http_request(accessToken).get(Urls.refreshAccessToken.value, {'token': accessToken})

    def removeAccessToken(self, accessToken):
        return self._get_http_request(accessToken).get(Urls.removeAccessToken.value, {'token': accessToken})
